<template>
<div>
    <div class="top-bar">
        <el-button type="primary" icon="el-icon-edit" @click="addActivity()">添加活动</el-button>
        <el-input
            v-model="searchKeyword"
            placeholder="请输入活动名称进行搜索"
            style="width: 300px; margin-left: 10px;"
            @keyup.enter="handleSearch"
            clearable>
            <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
        </el-input>
    </div>
    <el-col :span="23" class="data-table">
        <el-table :data="tableData" border style="width: 100%">
            <el-table-column label="ID" width="80px" sortable fixed>
                <template slot-scope="scope">
                    <span>{{ scope.row.activityID }}</span>
                </template>
            </el-table-column>
            <el-table-column label="活动名称" width="200px;">
                <template slot-scope="scope">
                    <el-popover trigger="hover" placement="top">
                        <p><i style="color:rgb(64,158,255);" class="el-icon-info">活动名称</i>&nbsp;&nbsp;{{ scope.row.activityTitle }}</p>
                        <p><i style="color:rgb(64,158,255);" class="el-icon-s-promotion">活动时间</i>&nbsp;&nbsp;{{ scope.row.activityDate }}</p>
                        <p><i style="color:rgb(64,158,255);" class="el-icon-location">活动地址</i>&nbsp;&nbsp;{{ scope.row.activityAddress }}</p>
                        <p><i style="color:rgb(64,158,255);" class="el-icon-s-ticket">活动价格</i>&nbsp;&nbsp;{{ scope.row.activityPrice }}</p>
                        <p><i style="color:rgb(64,158,255);" class="el-icon-s-comment">活动介绍</i>&nbsp;&nbsp;{{ scope.row.activityDesc }}</p>
                        <img :src="scope.row.activityPicture" style="height:300px" />
                        <div slot="reference" class="name-wrapper">
                            <span style="color:rgb(64,158,255);">{{ scope.row.activityTitle }}</span>
                        </div>
                    </el-popover>
                </template>
            </el-table-column>
            <el-table-column label="活动地址" width="300px;" sortable>
                <template slot-scope="scope">
                    <span>{{ scope.row.activityAddress }}</span>
                </template>
            </el-table-column>
            <el-table-column label="活动时间" width="200px;" sortable>
                <template slot-scope="scope">
                    <span>{{ scope.row.activityDate }}</span>
                </template>
            </el-table-column>
            <el-table-column label="活动价格" width="140px;" sortable>
                <template slot-scope="scope">
                    <span>{{ scope.row.activityPrice }}</span>
                </template>
            </el-table-column>
            <el-table-column label="活动状态" width="140px;" sortable>
                <template slot-scope="scope">
                    <span>{{ scope.row.activityStatus }}</span>
                </template>
            </el-table-column>
            <el-table-column label="推荐星级" width="140px;" sortable>
                <template slot-scope="scope">
                    <span>{{ scope.row.activityStar }}</span>
                </template>
            </el-table-column>
			<el-table-column label="发布者" width="150px" sortable>
                <template slot-scope="scope">
                    <span style="margin-left: 10px">{{ scope.row.activityAuthor }}</span>
                </template>
            </el-table-column>
			<el-table-column label="发布时间" width="200px;" sortable>
                <template slot-scope="scope">
                    <span>{{ scope.row.activityOnDate }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="150px" fixed="right">
                <template slot-scope="scope">
<!--                    <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>-->
					<el-button size="mini" type="primary" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[5, 10, 20, 40]" :page-size="pagesize" layout="total, sizes, prev, pager, next, jumper" :total="totalCount">
        </el-pagination>
    </el-col>

    <!-- 添加/编辑活动对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="40%">
        <el-form :model="form" :rules='rules' ref="form" label-width="80px">
			<el-alert v-if="editable" title="管理员无法修改图片内容" type="warning" style="margin-bottom: 20px; margin-top:-20px;"></el-alert>
            <el-form-item label="活动名称" prop="activityTitle">
                <el-input v-model="form.activityTitle"></el-input>
            </el-form-item>
            <el-form-item label="活动介绍" prop="activityDesc">
                <el-input type="textarea" v-model="form.activityDesc" :rows="4"></el-input>
            </el-form-item>
            <el-form-item label="活动地址" prop="activityAddress">
                <el-input v-model="form.activityAddress"></el-input>
            </el-form-item>
            <el-form-item label="活动时间" prop="activityDate">
                <el-date-picker v-model="form.activityDate" type="datetime" placeholder="选择活动时间" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="活动价格" prop="activityPrice">
                <el-input v-model="form.activityPrice" @input="validatePrice" placeholder="请输入价格（数字）"></el-input>
            </el-form-item>
            <el-form-item label="联系电话" prop="activityPhone">
                <el-input v-model="form.activityPhone" maxlength="11" @input="validatePhone" placeholder="请输入11位手机号码"></el-input>
            </el-form-item>
            <!-- <el-form-item label="活动状态" prop="activityStatus">
                <el-select v-model="form.activityStatus" placeholder="请选择活动状态">
                    <el-option label="进行中" value="进行中"></el-option>
                    <el-option label="已结束" value="已结束"></el-option>
                    <el-option label="即将开始" value="即将开始"></el-option>
                    <el-option label="已取消" value="已取消"></el-option>
                </el-select>
            </el-form-item> -->
            <el-form-item label="推荐星级" prop="activityStar">
                <el-select v-model="form.activityStar" placeholder="请选择星级">
                    <el-option label="0星" value="0"></el-option>
                    <el-option label="1星" value="1"></el-option>
                    <el-option label="2星" value="2"></el-option>
                    <el-option label="3星" value="3"></el-option>
                    <el-option label="4星" value="4"></el-option>
                    <el-option label="5星" value="5"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="活动图片" prop="activityPicture" v-if="!isEdit">
                <el-upload class="avatar-uploader" action="http://localhost:8080/uploadPicture" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                    <img v-if="imageUrl" :src="imageUrl" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </el-form-item>
<!--            <el-form-item label="发布者" prop="activityAuthor" v-if="!isEdit">-->
<!--                <el-input v-model="form.activityAuthor"></el-input>-->
<!--            </el-form-item>-->
			<el-form-item label="发布者">
                <el-input v-model=userName :disabled=true></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
    </el-dialog>
</div>
</template>

<script>
const axios = require('axios')
const qs = require('qs')
const ele = require('element-ui')

export default {
    name: 'manageActivity',
    data() {
        return {
            tableData: [],
            currentPage: 1,
            pagesize: 10,
            totalCount: 0,
            searchKeyword: '',
            dialogVisible: false,
            dialogTitle: '添加活动',
            isEdit: false,
            imageUrl: '',
			userName: '',
            form: {
                activityTitle: '',
                activityDesc: '',
                activityAuthor: '',
                activityPicture: '',
                activityDate: '',
                activityPrice: '',
                activityPhone: '',
                activityStatus: '',
                activityStar: '',
                activityAddress: ''
            },
			// 修改公告时不能编辑图片
            editable: true,
			rules: {
                activityTitle: [{
                    required: true,
                    message: '必填项',
                    trigger: 'blur'
                }],
                activityDesc: [{
                    required: true,
                    message: '必填项',
                    trigger: 'blur'
                }],
                activityDate: [{
                    required: true,
                    message: '必填项',
                    trigger: 'blur'
                }],
                activityPrice: [{
                    required: true,
                    message: '必填项',
                    trigger: 'blur'
                }],
                activityPhone: [{
                    required: true,
                    message: '必填项',
                    trigger: 'blur'
                }],
                activityStar: [{
                    required: true,
                    message: '必填项',
                    trigger: 'blur'
                }],
				activityAddress: [{
                    required: true,
                    message: '必填项',
                    trigger: 'blur'
                }]
            }
        }
    },
    methods: {
        // 验证电话号码
        validatePhone(value) {
            // 只允许输入数字
            this.form.activityPhone = value.replace(/\D/g, '');
            
            // 验证长度
            if (this.form.activityPhone.length > 0 && this.form.activityPhone.length !== 11) {
                this.$message.warning('请输入11位手机号码');
            }
        },
        
        // 验证价格
        validatePrice(value) {
            // 只允许输入数字和小数点
            this.form.activityPrice = value.replace(/[^\d.]/g, '');
            
            // 防止多个小数点
            const parts = this.form.activityPrice.split('.');
            if (parts.length > 2) {
                this.form.activityPrice = parts[0] + '.' + parts.slice(1).join('');
            }
        },
        // 加载数据
        loadData() {
            let _this = this
            axios({
                method: 'get',
                url: 'http://localhost:8080/getActivityList',
                params: {
                    searchKeyword: this.searchKeyword,
                    page: this.currentPage,
                    pageSize: this.pagesize
                },
                headers: {
                    'Content-type': 'application/x-www-form-urlencoded'
                }
            }).then(function (response) {
                _this.tableData = response.data.dataList
                _this.totalCount = response.data.totalCount
            }).catch(function (error) {
                console.log(error)
            })
        },
        // 搜索功能
        handleSearch() {
            this.currentPage = 1
            this.loadData()
        },
        // 获取活动列表
        getActivityList() {
            let _this = this
            _this.loadData()
        },
        // 添加活动
        addActivity() {
            this.dialogTitle = '添加活动'
            this.isEdit = false
            this.dialogVisible = true
            this.resetForm()
        },
        // 编辑活动
        handleEdit(index, row) {
            this.dialogTitle = '编辑活动'
            this.isEdit = true
            this.dialogVisible = true
            this.form = {
                activityID: row.activityID,
                activityTitle: row.activityTitle,
                activityDesc: row.activityDesc,
                activityAuthor: row.activityAuthor,
                activityPicture: row.activityPicture,
                activityDate: row.activityDate,
                activityPrice: row.activityPrice,
                activityPhone: row.activityPhone,
                activityStatus: row.activityStatus,
                activityStar: row.activityStar,
                activityAddress: row.activityAddress
            }
        },
        // 删除活动
        handleDelete(index, row) {
            this.$confirm('确认删除该活动?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let _this = this
                axios({
                    method: 'post',
                    url: 'http://localhost:8080/deleteActivity',
                    headers: {
                        'Content-type': 'application/x-www-form-urlencoded'
                    },
                    data: qs.stringify({
                        activityID: row.activityID
                    })
                }).then(function (response) {
                    if (response.data.status === 'success') {
                        ele.Message.success('删除成功')
                        _this.getActivityList()
                    } else {
                        ele.Message.error('删除失败')
                    }
                }).catch(function (error) {
                    console.log(error)
                    ele.Message.error('删除失败')
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                })
            })
        },
        // 提交表单
        submitForm() {
            let _this = this
            if (this.isEdit) {
                // 编辑活动
                axios({
                    method: 'post',
                    url: 'http://localhost:8080/updateActivity',
                    headers: {
                        'Content-type': 'application/x-www-form-urlencoded'
                    },
                    data: qs.stringify({
                        activityID: this.form.activityID,
                        activityTitle: this.form.activityTitle,
                        activityDesc: this.form.activityDesc,
                        activityAddress: this.form.activityAddress,
                        activityPrice: this.form.activityPrice,
                        activityPhone: this.form.activityPhone,
                        activityStar: this.form.activityStar,
						activityAuthor: this.form.activityAuthor,
						activityPicture: this.form.activityPicture,
						activityDate: this.form.activityDate
                    })
                }).then(function (response) {
                    if (response.data.status === 'success') {
                        ele.Message.success('更新成功')
                        _this.dialogVisible = false
                        _this.getActivityList()
                    } else {
                        ele.Message.error('更新失败')
                    }
                }).catch(function (error) {
                    console.log(error)
                    ele.Message.error('更新失败')
                })
            } else {
                // 添加活动
                axios({
                    method: 'post',
                    url: 'http://localhost:8080/addActivity',
                    headers: {
                        'Content-type': 'application/x-www-form-urlencoded'
                    },
                    data: qs.stringify({
                        activityTitle: this.form.activityTitle,
                        activityDesc: this.form.activityDesc,
                        activityAuthor: this.userName,
                        activityPicture: this.form.activityPicture,
                        activityDate: this.form.activityDate,
                        activityPrice: this.form.activityPrice,
                        activityPhone: this.form.activityPhone,
                        activityStatus: this.form.activityStatus,
                        activityStar: this.form.activityStar,
                        activityAddress: this.form.activityAddress
                    })
                }).then(function (response) {
                    if (response.data.status === 'success') {
                        ele.Message.success('添加成功')
                        _this.dialogVisible = false
                        _this.getActivityList()
                    } else {
                        ele.Message.error('添加失败')
                    }
                }).catch(function (error) {
                    console.log(error)
                    ele.Message.error('添加失败')
                })
            }
        },
        // 重置表单
        resetForm() {
            this.form = {
                activityTitle: '',
                activityDesc: '',
                activityAuthor: '',
                activityPicture: '',
                activityDate: '',
                activityPrice: '',
                activityPhone: '',
                activityStatus: '',
                activityStar: '',
                activityAddress: ''
            }
            this.imageUrl = ''
        },
        // 图片上传成功
        handleAvatarSuccess(res, file) {
            if (!res || !res.imgURL) {
                this.$message.error('图片上传成功，但未返回有效路径')
                return
            }
            this.imageUrl = URL.createObjectURL(file.raw)
            this.form.activityPicture = res.imgURL
            // this.imageUrl = URL.createObjectURL(file.raw)
            // this.form.activityPicture = res.imgURL
        },
        // 图片上传前验证
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
            const isLt2M = file.size / 1024 / 1024 < 2

            if (!isJPG) {
                this.$message.error('上传图片只能是 JPG/PNG 格式!')
            }
            if (!isLt2M) {
                this.$message.error('上传图片大小不能超过 2MB!')
            }
            return isJPG && isLt2M
        },
        // 分页处理
        handleSizeChange(val) {
            this.pagesize = val
        },
        handleCurrentChange(val) {
            this.currentPage = val
        }
    },
    created() {

		if (window.localStorage.getItem('userType') != 'admin') {
            ele.Message.error("你没有管理员权限访问后台，即将跳转到登录页面")
            this.$router.push('/login')
        } else {
			this.userName = window.localStorage.getItem('userName')
			this.getActivityList()
        }
    }
}
</script>

<style scoped>
.top-bar {
    margin-bottom: 20px;
}

.data-table {
    margin-top: 20px;
}

.name-wrapper {
    cursor: pointer;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
